# 2.使用蓝图对象创建路由
from flask import current_app, render_template, session, jsonify, abort, request, g

from info.modules.home import home_blu
from info import rs
import logging

from info.utils.common import user_login_data
from info.utils.constants import HOME_PAGE_MAX_NEWS
from info.utils.models import User, News, Category
from info.utils.response_code import error_map, RET


# 网站首页
@home_blu.route('/')
@user_login_data
def index():
    # 查询点击量排行前10的新闻
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)
        rank_list = []

    # 查询所有的分类数据
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    user = g.user.to_dict() if g.user else None

    # 将排行前10的新闻数据传入模板渲染
    return render_template("index.html", user=user, rank_list=rank_list, categories=categories)


@home_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


# 获取新闻列表
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get('cid')
    cur_page = request.args.get('cur_page')
    per_count = request.args.get('per_count', HOME_PAGE_MAX_NEWS)
    # 校验参数
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        cid = int(cid)
        cur_page = int(cur_page)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 数据库行为:按照分类,页码查询新闻 发布时间倒序
    filter_list = []
    if cid != 1:
        filter_list.append(News.category_id == cid)

    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # try:
    #     if cid != 1:
    #         pn = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(cur_page,per_count)
    #
    #     else:
    #         pn = News.query.order_by(News.create_time.desc()).paginate(cur_page,per_count)
    #
    # except BaseException as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 返回数据
    data = {
        'news_list': [news.to_dict() for news in pn.items],
        'total_page': pn.pages
    }

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
